import i18n from '~/i18n/index'
import type { FormInstance } from 'element-plus'

/**
 * 对话框插件，提供基本的详情，新增，编辑
 * @param title 对话框标题主题，如新增【分类】，编辑【分类】里面的封【分类】，会自动在前面添加新增编辑等
 * @returns
 */
export function useDD<T = any>(title: string) {
  /**
   * 对话框数据信息
   */
  const dd = reactive({
    show: false,
    loading: false,
    disable: false,
    action: 0 as ListAction,
    title: '',
    item: {} as Ref<T>
  })

  /**
   * 打开对话框
   * @param action 类型 0添加，1详情，2修改
   * @param row  列表的数据
   */
  const openDD = (action: ListAction, row?: T) => {
    dd.show = true
    dd.action = action
    dd.disable = action == 1
    if (action == 0) {
      dd.item = {} as T
      dd.title = i18n.global.t('common.ddAdd', { dd: title })
    } else if (action == 1) {
      dd.title = i18n.global.t('common.ddDetail', { dd: title })
      dd.item = row!
    } else {
      dd.title = i18n.global.t('common.ddEdit', { dd: title })
      dd.item = row!
    }
  }

  const confirmDD = async (saveApi?: SaveApiCall<any>, afterSave?: Function, formRef?: Ref<FormInstance>) => {
    if (dd.action !== 1) {
      let validStatus = true
      if (formRef) {
        validStatus = false
        validStatus = await formRef.value.validate()
      }
      if (saveApi && validStatus) {
        saveApi(dd.item, dd).then(() => {
          dd.show = false
          afterSave && afterSave()
        })
      }
    } else {
      dd.show = false
    }
  }

  return {
    dd,
    openDD,
    confirmDD
  }
}
